<?php

abstract class App_Api
{
    protected $lgMode;
    protected $_uid;

    public function __construct($lgMode = "pri")
    {
        $this->lgMode = $lgMode;
    }

    protected function checkAuth()
    {
        if ($this->lgMode == "pri")
        {
            // 获得login uid，并检测是否自动登录
            $this->_uid = $this->getLoginUid();
            if (!$this->_uid)
            {
                header("HTTP/1.0 401 Unauthorized");
                exit;
            }
            Context_Object::set("uid" , $this->_uid);
        }
    }

    protected function getLoginUid() {

        $apiAuth = new Api_Auth();
        $_uid = 0;

        // session 阶段cookie验证
        $_user = Tool_Input::clean("c", "_kxcapiuser", "str");
        $res = $apiAuth->checkSessionToken(array("token" => $_user));
        $_uid = $res["uid"];

        // 持久cookie验证
        if(!$_uid)
        {
            $_api = Tool_Input::clean("c", "_kxcapi", "str");
            $res = $apiAuth->checkPersistToken(array("token" => $_api));
            if ($res["uid"] > 0)
            {
                $_uid = $res["uid"];
                $this->setPersistCookie($res["newToken"]);
            }
        }

        // 检测主站 jipin.kaixin001.com的登录状态
        if(!$_uid) {
            $_logout = Tool_Input::clean("c", "_kxcapilogout", "str");
            if(empty($_logout))
            {
                $_kxcuser = Tool_Input::clean("c", "_kxcuser", "str");
                $res = $apiAuth->checkSessionToken(array("token" => $_kxcuser));
                $_uid = $res["uid"];
				if(!empty($_uid)) {
	                $apiAuth->doLogin(array(
	                    "uid" => $_uid,
	                    "ip"  => Tool_Ip::getClientIP(),
	                ));
				}
            }
        }
        if ($_uid)
        {
            $cuserInfo = new CUser_Info();
            $state = $cuserInfo->getState($_uid);
            if ($state == 1 || $state == 2)
            {
                $this->clearCookie();
                $_uid = 0;
            }
        }
        return $_uid;
    }

    protected function setCookie($remember = false)
    {
        $apiAuth = new Api_Auth();
        header("P3P: CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");
        $arr = $apiAuth->createSessionToken(array("uid" => $this->_uid));
        setcookie("_kxcapiuser", $arr["token"], 0, "/", WWW_HOST);
        setcookie("_kxcapiuid", $this->_uid, 0, "/", WWW_HOST);
        if($remember) {
            $arr = $apiAuth->createPersistToken(array("uid" => $this->_uid));
            $this->setPersistCookie($arr["token"]);
        }
    }

    protected function setPersistCookie($token)
    {
        setcookie("_kxcapi", $token, time() + 30 * 86400, "/", WWW_HOST);
    }

    protected function clearCookie()
    {
        setcookie('_kxcapiuser', '', -86400, '/', WWW_HOST);
        setcookie('_kxcapi', '', -86400, '/', WWW_HOST);
        setcookie('_kxcapilogout', '1', time() + 365 * 86400 , '/', WWW_HOST);
    }

    public function run()
    {
        try
        {
            $this->getPara();

            $this->checkAuth();

            $this->main();

            $responseData = $this->getResponseData();
            $this->render($responseData);
        }
        catch (Exception $e)
        {
            //统一异常处理
            Tool_Log::debug("exception", getenv("REQUEST_URI")."\t"
                .Context_Object::o("uid")."\t"
                .$e->getCode()."\t".$e->getMessage()."\n");

            $this->render(array(
                "error" => array(
                    "errno" => $e->getCode(),
                    "error" => $e->getMessage(),
                ),
            ));
        }
    }

    protected function render($responseData)
    {
        if (!headers_sent())
        {
            header("Cache-Control: no-cache");
            header("Pragma: no-cache");
        }

        if (defined("KXC_DEBUG_MODE") && true == KXC_DEBUG_MODE)
        {
            $responseData['xhprof'] = $this->getXhInfo();
        }
        $this->setCookie();
        echo json_encode($responseData);
    }

    abstract protected function getPara();

    abstract protected function main();

    abstract protected function getResponseData();

    private function getXhInfo()
    {
        $profiler_namespace = 'kxc_pic_api';
        $xhprof_data = xhprof_disable();
        $xhprof_runs = new XHProfRuns_Default();
        $run_id = $xhprof_runs->save_run($xhprof_data, $profiler_namespace);
        $profiler_url = sprintf('http://'.PIC_NORMAL_WWW_HOST.'/test/xhprof_html/index.php?run=%s&source=%s', $run_id, $profiler_namespace);

        $info = array('url'=>$profiler_url);
        return $info;
    }
}

?>